package com.jjzy;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;

/**
 * Author:   wj
 * Date:     2020/2/7 15:18
 * Description: 测试认证
 */
public class Main {
    private static final transient Logger log = LoggerFactory.getLogger(Main.class);

    public static void main(String[] args) {
        //创建用户名密码
        String name = "wj";
        String pass = "123456";

        // 1，创建安全管理器的工厂对象
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        // 2,使用工厂创建安全管理器
        SecurityManager securityManager = factory.getInstance();
        // 3,把当前的安全管理器绑定当到前的线程
        SecurityUtils.setSecurityManager(securityManager);
        // 4,使用SecurityUtils.getSubject得到主体对象
        Subject subject = SecurityUtils.getSubject();
        // 5，封装用户名和密码
        AuthenticationToken token = new UsernamePasswordToken(name, pass);

        //得到认证
        try {
            subject.login(token);
            log.info("认证成功");
        } catch (AuthenticationException e) {
            log.error("认证失败");
        }

        //授权
        //判断是否拥有某个角色
        log.info("授权测试--------------");
        boolean hasRole = subject.hasRole("role1");
        System.out.println("拥有role1"+hasRole);
        System.out.println("hasRole = " + hasRole);

        //判断 是否 分别 拥有组里面的角色
        boolean[] hasRoles = subject.hasRoles(Arrays.asList("role1", "role2", "role3"));

        for (int i = 0; i < hasRoles.length; i++) {
            System.out.println("是否拥有"+hasRoles[i]);
        }
        //判断 是否拥有组里面的全部角色
        boolean hasAllRoles = subject.hasAllRoles(Arrays.asList("role1", "role2", "role3"));
        System.out.println(hasAllRoles);

        //判断是否拥有权限
        boolean permitted = subject.isPermitted("user:add");
        System.out.println(permitted);

        //判断是否拥有权限组
        boolean[] permitted1 = subject.isPermitted("user:add", "user:query");
        for (int i = 0; i <permitted1.length ; i++) {
            System.out.println(permitted1[i]);
        }





    }
}
